package com.guofen.service.user.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guofen.dao.UserMapper;
import com.guofen.pojo.User;
import com.guofen.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public User login(String name, String password) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("password", password);
        return userMapper.selectByNamePassword(map);
    }

    @Override
    public Map<String, Object> get(String name, int pageSize, int currentPage) {
        Map<String, Object> map = new HashMap<>();
        PageHelper.startPage(currentPage, pageSize);
        List<User> list = userMapper.selectByName(name);
        PageInfo pageUser = new PageInfo(list);
        long sum = pageUser.getTotal();
        list = pageUser.getList();
        map.put("user",list);
        map.put("sum",sum);
        return map;
    }

    @Override
    public boolean add(User user) {
        if (userMapper.selectByNameUnique(user.getName()) > 0) {
            return false;
        }
        return userMapper.insertSelective(user);
    }

    @Override
    public boolean delete(int id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public boolean update(User user) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("name", user.getName());
        if (userMapper.selectByNameUniqueExpectId(map) > 0)
            return false;
        return userMapper.updateByPrimaryKeySelective(user);
    }
}
